package cn.hfatec.shms.system.upload.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.app.AppContext;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.constants.ShmsProperties;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author: panwb
 * <p/>
 * Date: 2015/11/24
 * Time: 9:53
 */
@Service("UploadService")
public class UploadService {

    // 获取文件扩展名
    private static String getFileExt(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        }

        return "";
    }

    /**
     * 上传文件到临时目录
     *
     * @param file
     * @param fileType
     * @param request
     * @return
     */
    @MysqlDataSource
    public String uploadFile(MultipartFile file, String fileType, HttpServletRequest request) throws IOException {

        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);

        String realPath = shmsProperties.getUploadPath();
        String tempPath = shmsProperties.getUploadTempPath();


        if (!StringUtils.isEmpty(fileType)) {//fileType非空时校验
            String fileExt = getFileExt(file.getOriginalFilename());
            if (StringUtils.isEmpty(fileExt)) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "请选择要上传文件,该功能上传文件格式为" + fileType, "").toString();
            } else {
                if (!StringUtils.isEmpty(fileType)) {
                    boolean flag = false;
                    String[] checkFileNames = fileType.split(",");
                    for (String checkFileName : checkFileNames) {
                        if (!flag) {
                            if (fileExt.equals(checkFileName)) {
                                flag = true;//校验通过
                            }
                        }
                    }
                    if (!flag) {
                        return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "上传的文件格式错误,该功能上传文件格式必须为" + fileType, "").toString();
                    }
                }
            }
        }


        String savePath = new StringBuilder(realPath).append(tempPath).append(File.separator).append(request.getSession().getId()).toString();
        if (file.getSize() > 0) {
            File filePath = new File(savePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            String originalFileName = file.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
            File tempFile = new File(savePath + File.separator + System.currentTimeMillis() + suffix);
            OutputStream outputStream = new FileOutputStream(tempFile);
            IOUtils.copy(file.getInputStream(), outputStream);
            IOUtils.closeQuietly(outputStream);

            StringBuilder fileSavePath = new StringBuilder().append("/upload/");
            fileSavePath.append(tempPath);
            fileSavePath.append(File.separator);
            fileSavePath.append(request.getSession().getId());
            fileSavePath.append(File.separator);
            fileSavePath.append(tempFile.getName()).toString();

            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "文件上传成功", fileSavePath.toString()).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "请选择要上传文件", "").toString();
    }
}
